import React, { useState } from 'react'
import { 
  Card, 
  Row, 
  Col, 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  notification,
  Popconfirm,
  Typography,
  Alert,
} from 'antd'
import { 
  UserOutlined, 
  PlusOutlined, 
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CrownOutlined,
  SettingOutlined,
} from '@ant-design/icons'
import { useQuery, useMutation, useQueryClient } from 'react-query'
import { authApi, UserRegister } from '../services/auth'
import { useAuth } from '../hooks/useAuth'

const { Title, Text } = Typography
const { Option } = Select

interface MockUser {
  id: string
  username: string
  email: string
  full_name?: string
  role: string
  is_active: boolean
  created_at: string
  last_login?: string
}

const UserManagement: React.FC = () => {
  const { user: currentUser, hasRole } = useAuth()
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [selectedUser, setSelectedUser] = useState<MockUser | null>(null)
  const [form] = Form.useForm()
  const queryClient = useQueryClient()

  // 模拟用户数据
  const mockUsers: MockUser[] = [
    {
      id: '1',
      username: 'admin',
      email: 'admin@example.com',
      full_name: '系统管理员',
      role: 'admin',
      is_active: true,
      created_at: '2024-01-01T00:00:00Z',
      last_login: '2024-08-27T10:00:00Z',
    },
    {
      id: '2', 
      username: 'operator',
      email: 'operator@example.com',
      full_name: '操作员',
      role: 'operator',
      is_active: true,
      created_at: '2024-01-15T00:00:00Z',
      last_login: '2024-08-26T15:30:00Z',
    },
    {
      id: '3',
      username: 'viewer',
      email: 'viewer@example.com', 
      full_name: '观察者',
      role: 'viewer',
      is_active: true,
      created_at: '2024-02-01T00:00:00Z',
      last_login: '2024-08-25T09:15:00Z',
    },
  ]

  // 创建用户mutation
  const createUserMutation = useMutation(authApi.register, {
    onSuccess: () => {
      notification.success({
        message: '创建成功',
        description: '用户创建成功',
      })
      setCreateModalVisible(false)
      form.resetFields()
      queryClient.invalidateQueries('users')
    },
    onError: (error: any) => {
      notification.error({
        message: '创建失败',
        description: error.message || '创建用户失败',
      })
    },
  })

  // 处理创建用户
  const handleCreateUser = async (values: UserRegister) => {
    await createUserMutation.mutateAsync(values)
  }

  // 处理编辑用户
  const handleEditUser = (user: MockUser) => {
    setSelectedUser(user)
    form.setFieldsValue(user)
    setEditModalVisible(true)
  }

  // 处理删除用户
  const handleDeleteUser = (userId: string) => {
    notification.info({
      message: '演示模式',
      description: '演示模式下无法删除用户',
    })
  }

  // 获取角色颜色
  const getRoleColor = (role: string) => {
    switch (role) {
      case 'admin': return 'red'
      case 'operator': return 'blue'
      case 'viewer': return 'green'
      default: return 'default'
    }
  }

  // 获取角色图标
  const getRoleIcon = (role: string) => {
    switch (role) {
      case 'admin': return <CrownOutlined />
      case 'operator': return <SettingOutlined />
      case 'viewer': return <EyeOutlined />
      default: return <UserOutlined />
    }
  }

  // 获取角色显示名称
  const getRoleDisplayName = (role: string) => {
    switch (role) {
      case 'admin': return '管理员'
      case 'operator': return '操作员'
      case 'viewer': return '查看者'
      default: return role
    }
  }

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text: string, record: MockUser) => (
        <Space>
          <UserOutlined />
          <Text strong={record.id === currentUser?.id}>
            {text}
            {record.id === currentUser?.id && <Tag color="blue" style={{ marginLeft: 8 }}>当前用户</Tag>}
          </Text>
        </Space>
      )
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '姓名',
      dataIndex: 'full_name',
      key: 'full_name',
      render: (text: string) => text || '-'
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => (
        <Tag color={getRoleColor(role)} icon={getRoleIcon(role)}>
          {getRoleDisplayName(role)}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'green' : 'red'}>
          {isActive ? '激活' : '禁用'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => new Date(date).toLocaleDateString()
    },
    {
      title: '最后登录',
      dataIndex: 'last_login',
      key: 'last_login',
      render: (date: string) => date ? new Date(date).toLocaleString() : '从未登录'
    },
    {
      title: '操作',
      key: 'action',
      render: (record: MockUser) => (
        <Space size="small">
          <Button 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEditUser(record)}
            disabled={!hasRole('admin')}
          >
            编辑
          </Button>
          <Popconfirm
            title="确认删除用户？"
            description="此操作不可恢复"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确认"
            cancelText="取消"
            disabled={!hasRole('admin') || record.id === currentUser?.id}
          >
            <Button 
              size="small" 
              danger
              icon={<DeleteOutlined />}
              disabled={!hasRole('admin') || record.id === currentUser?.id}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    },
  ]

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Title level={2} style={{ marginBottom: 8 }}>
          <UserOutlined style={{ marginRight: 8, color: '#1890ff' }} />
          用户管理
        </Title>
        <Text type="secondary">
          管理系统用户账户、角色权限和访问控制
        </Text>
      </div>

      {!hasRole('admin') && (
        <Alert
          message="权限提示"
          description="您当前是查看模式，只能浏览用户信息，无法进行管理操作"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      {/* 用户统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                {mockUsers.length}
              </div>
              <div style={{ color: '#666' }}>总用户数</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                {mockUsers.filter(u => u.is_active).length}
              </div>
              <div style={{ color: '#666' }}>活跃用户</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#ff4d4f' }}>
                {mockUsers.filter(u => u.role === 'admin').length}
              </div>
              <div style={{ color: '#666' }}>管理员</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#722ed1' }}>
                {mockUsers.filter(u => u.last_login).length}
              </div>
              <div style={{ color: '#666' }}>已登录</div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 用户列表 */}
      <Card 
        title="用户列表" 
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
            disabled={!hasRole('admin')}
          >
            添加用户
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={mockUsers}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 个用户`,
          }}
        />
      </Card>

      {/* 创建用户Modal */}
      <Modal
        title="添加新用户"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateUser}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名至少3个字符' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="输入用户名" />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱地址"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="输入邮箱地址" />
          </Form.Item>

          <Form.Item
            name="full_name"
            label="姓名"
          >
            <Input placeholder="输入真实姓名" />
          </Form.Item>

          <Form.Item
            name="role"
            label="用户角色"
            initialValue="viewer"
            rules={[{ required: true, message: '请选择用户角色' }]}
          >
            <Select>
              <Option value="viewer">查看者</Option>
              <Option value="operator">操作员</Option>
              <Option value="admin">管理员</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password placeholder="输入初始密码" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setCreateModalVisible(false)}>
                取消
              </Button>
              <Button 
                type="primary" 
                htmlType="submit"
                loading={createUserMutation.isLoading}
              >
                创建
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑用户Modal */}
      <Modal
        title="编辑用户"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={500}
      >
        <Alert
          message="演示模式"
          description="当前为演示模式，编辑功能暂不可用"
          type="info"
          style={{ marginBottom: 16 }}
        />
        <Form
          form={form}
          layout="vertical"
          disabled
        >
          <Form.Item name="username" label="用户名">
            <Input prefix={<UserOutlined />} />
          </Form.Item>
          <Form.Item name="email" label="邮箱地址">
            <Input />
          </Form.Item>
          <Form.Item name="full_name" label="姓名">
            <Input />
          </Form.Item>
          <Form.Item name="role" label="用户角色">
            <Select>
              <Option value="viewer">查看者</Option>
              <Option value="operator">操作员</Option>
              <Option value="admin">管理员</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default UserManagement